
package com.xifan.myaccount.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class ImageUtil {
    private static final String PICTURE_STORAGE_SUFFIX = "-date.jpg";

    public static File getDefaultPicPath() {
        SimpleDateFormat sdf = Util.getDateFormatter("yyyyMMddHHmm");
        return new File(Util.getAppPath() + File.separator
                + sdf.format(Calendar.getInstance().getTime())
                + PICTURE_STORAGE_SUFFIX);
    }

    public static Bitmap ImageCrop(Bitmap bitmap, DisplayMetrics metrics, File picPath,
            boolean needCompress)
            throws IOException {
        float w = bitmap.getWidth();
        float h = bitmap.getHeight();
        int screenW = metrics.widthPixels;
        // TODO GET right height
        int screenH = metrics.heightPixels - 96;
        Log.e("xifan", "h=" + h + " w=" + w + "screenW=" + screenW + "screenH=" + screenH
                + " needCompress = " + needCompress);

        if (w >= screenW && h >= screenH) {
            float ratio, scaledH, scaledW, offsetW = 0, offsetH = 0f;
            if ((h / w) > ((float) screenH / (float) screenW)) {
                ratio = w / (float) screenW;
                scaledH = h / ratio;
                offsetH = (scaledH - (float) screenH) / 2f;
                bitmap = Bitmap.createScaledBitmap(bitmap, screenW, (int) scaledH, true);
            } else {
                ratio = h / (float) screenH;
                scaledW = w / ratio;
                offsetW = (scaledW - (float) screenW) / 2f;
                bitmap = Bitmap.createScaledBitmap(bitmap, (int) scaledW, screenH, true);
            }

            // save croped bitmap with/whithout compress
            Log.e("xifan", "picpath = " + picPath.getPath());
            FileOutputStream output = new FileOutputStream(picPath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, needCompress ? 85 : 100, output);
            output.flush();
            output.close();

            return Bitmap.createBitmap(bitmap, (int) offsetW, (int) offsetH, screenW, screenH);
        } else {
            // bitmap is smaller than screen
            FileOutputStream output = new FileOutputStream(picPath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, needCompress ? 85 : 100, output);
            output.flush();
            output.close();
            return bitmap;
        }
    }

    @SuppressWarnings("unused")
    private Bitmap blurImageAmeliorate(Bitmap bmp)
    {
        long start = System.currentTimeMillis();
        // 高斯矩阵
        int[] gauss = new int[] {
                1, 2, 1, 2, 4, 2, 1, 2, 1
        };

        int width = bmp.getWidth();
        int height = bmp.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);

        int pixR = 0;
        int pixG = 0;
        int pixB = 0;

        int pixColor = 0;

        int newR = 0;
        int newG = 0;
        int newB = 0;

        int delta = 16; // 值越小图片会越亮，越大则越暗

        int idx = 0;
        int[] pixels = new int[width * height];
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);
        for (int i = 1, length = height - 1; i < length; i++)
        {
            for (int k = 1, len = width - 1; k < len; k++)
            {
                idx = 0;
                for (int m = -1; m <= 1; m++)
                {
                    for (int n = -1; n <= 1; n++)
                    {
                        pixColor = pixels[(i + m) * width + k + n];
                        pixR = Color.red(pixColor);
                        pixG = Color.green(pixColor);
                        pixB = Color.blue(pixColor);

                        newR = newR + (int) (pixR * gauss[idx]);
                        newG = newG + (int) (pixG * gauss[idx]);
                        newB = newB + (int) (pixB * gauss[idx]);
                        idx++;
                    }
                }

                newR /= delta;
                newG /= delta;
                newB /= delta;

                newR = Math.min(255, Math.max(0, newR));
                newG = Math.min(255, Math.max(0, newG));
                newB = Math.min(255, Math.max(0, newB));

                pixels[i * width + k] = Color.argb(255, newR, newG, newB);

                newR = 0;
                newG = 0;
                newB = 0;
            }
        }

        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        long end = System.currentTimeMillis();
        Log.d("may", "used time=" + (end - start));
        return bitmap;
    }

    public static Bitmap getPicFromCamera(Context context, File picPath) {
        try {
            DisplayMetrics metrics = Util.getDisplayMetrics((Activity) context);
            FileInputStream imgFile = new FileInputStream(picPath);
            Bitmap bitmap = ImageUtil.ImageCrop(BitmapFactory.decodeFile(picPath.getPath()),
                    metrics, picPath, imgFile.available() > Util.IMAGE_MAX_SIZE);
            imgFile.close();
            return bitmap;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap getPicFromAlbum(Context context, File picPath, Uri data) {
        try {
            DisplayMetrics metrics = Util.getDisplayMetrics((Activity) context);
            ContentResolver cr = context.getContentResolver();
            InputStream is = cr.openInputStream(data);
            Bitmap bitmap = ImageUtil.ImageCrop(BitmapFactory.decodeStream(is), metrics, picPath,
                    is.available() > Util.IMAGE_MAX_SIZE);
            is.close();
            return bitmap;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
